<?php

require_once('interfaces/RequestMapping.interface.php');
require_once('classes/Mapping/AbstractMappingConfig.class.php');

class RedirectMappingConfig extends AbstractMappingConfig implements RequestMapping{

    private $from;
    private $to;
    protected $parent;
    private $status;

    public function RedirectMappingConfig($fromUri, $toUri, $status = null){
        if ($status === null){
            $status = 302;
        }
        $this->status = $status;
        //if ($fromUri != $toUri){
            $this->from = $fromUri;
            $this->to = $toUri;
            return true;
        //}else{
            // Allow for now
            //throw new Exception('Can\'t redirect to self');
        //}
    }

    public function checkMapping($uri){
        if (!$this->configObj->conditionsMet()){
            return false;
        }
        $extArray = $this->parent->getDynamicExtention();
        if (!is_array($extArray) || count($extArray) == 0){
            $extArray = array('');
        }
        foreach ($extArray as $ext){
            if ($this->from.$ext == $uri && $this->from.$ext != $this->to){
                return true;
            }
        }
        return false;
    }

    public function run(){
        $this->configObj->run();
        header($_SERVER['SERVER_PROTOCOL'].' '.$this->status);
        header('location:'.$this->to);
        die('Redirecting');
    }

    public static function getXsdPart(){
        return '
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="from" type="xs:string" minOccurs="1" maxOccurs="1"/>
                            <xs:element name="to" type="xs:string" minOccurs="1" maxOccurs="1"/>
                            <xs:element name="status" type="xs:string" minOccurs="0" maxOccurs="1" default="302"/>
                        </xs:sequence>
                    </xs:complexType>
        ';
    }

    public static function interpretXmlConfig(/*XMLNodeList?*/ $xmlNodes, /*RequestInterpreter*/ $interpreter){
        for ($i = 0; $i < $xmlNodes->length; $i++){
            $item = $xmlNodes->item($i);

            $tmp_doc = new DOMDocument();
            $tmp_doc->appendChild($tmp_doc->importNode($item,true));

            $from = $tmp_doc->getElementsByTagName('from')->item(0);
            $to = $tmp_doc->getElementsByTagName('to')->item(0);
            $status = $tmp_doc->getElementsByTagName('status')->item(0);

            $interpreter->addMapping(new RedirectMappingConfig($from->textContent,$to->textContent,$status));
        }
    }

}

?>